Feedback - #1
Conversation
Added check for empty description and approvals check
In the future, you need to implement each declared method, it is possible to add private Also think about Generic and Comparable To when implementing these methods
feat: Complete binary search tree realization
… tree with the necessary balancing logic.
…string key in the neo4j database
| ) | ||
| return parse(nodesRecords) | ||
| } | ||
| fun unloadTree(): RedBlackTree<String>? { |
There was a problem hiding this comment.
У нас оно не работает(
Всегда возвращает null
| "CREATE (:node {key : \"${node.key}\", " + | ||
| "value: \"${node.value ?: ""}\", " + | ||
| "isBlack: ${node.color == BLACK}, " + | ||
| "lkey: \"${left?.key ?: ""}\", " + | ||
| "rkey: \"${right?.key ?: ""}\"}) " |
There was a problem hiding this comment.
Такой запрос уязвим к инъекциям. Через интерполяцию вставлять параметры очень опасно
* fix: Changed the files related to the project build and CI setup, changed mergeable * Issue #12 done (#18) * fix: Changed the logic of the findByKey function and initialization of trees * fix: Changed the initialization of trees in the database * fix: Rewrote all the bst methods without recursion and rewrote the tests for it * fix: Rewrote the AVL tree and tests for it * Refactor: rewrote the RBT and wrote tests for it [remove doesn't work!] * Issue #20 done (#23) * Feature: Added the ability to save string type keys in Sqlite database * Fix: solved the problem with gradle build * Issue #9 done implemented json repo to save trees with keys of type String and Int and values of type String * fix: Renamed function names to Json and SQLite repo Also add README * feature: Add jacoco coverage * fix: jacoco wrote differently in CI * fix: Found a bug in RBT remove * feature: Added tests for SQLite database * docs: Added explanations to the functions and removed unnecessary ones
…wing a tree with the necessary functionality for searching, inserting and removing with OpenRNDR library
olgsm
left a comment
There was a problem hiding this comment.
В целом, я бы больше сфокусировался не на алгоритмах поворота вершин (хотя если они корректные, вы молодцы) -- задание-то, кмк, раньше было не совсем и не только про это (поправьте меня, если я не прав). Задание про аккуратный ООП дизайн, конечно, и про проектирование архитектуры своей маленькой либы -- но как ее потенциально смогут использовать? покрыты ли все сценарии? есть ли документация? насколько это все расширяемо, можно ли будет добавлять еще виды деревьев? а другие базы данных? а если я захочу что-то визуализировать, как мне к вам втыкаться?) и прочее, и прочее)
Если вам интересно и в кайф такая разработка, советую потратить немного времени (пока оно есть лол), порефлексировать и допилить, это правда хороший опыт.
| dependencies { | ||
|
|
||
| // Neo4j | ||
| implementation("org.neo4j.driver", "neo4j-java-driver", "5.7.0") |
There was a problem hiding this comment.
В gradle проектах сейчас все чаще используют version-каталоги, советую почитать и потом перейти на их использование. Очень удобно шарить и контролировать версии зависимостей, особенно в большой монорепе с кучей саб-проектов
|
|
||
| import com.fasterxml.jackson.annotation.JsonIgnore | ||
|
|
||
| @Suppress("UNCHECKED_CAST") |
There was a problem hiding this comment.
Обычно если приходится писать @Suppress("UNCHECKED_CAST") на весь класс - это признак того, что с архитектурой что-то не так :)
| /** | ||
| * Adds a value to the tree by this key, if the key already exists, then overwrites the value | ||
| */ | ||
| open fun insert(key: K, value: V? = null) { |
There was a problem hiding this comment.
Публичные методы обычно ставят в начале файла, так удобнее читать код потом
| internal var right: Subtree? = null | ||
| internal var left: Subtree? = null | ||
| @JsonIgnore | ||
| open var parent: Subtree? = null |
There was a problem hiding this comment.
protected? или хотя бы internal, но вообще делать что-либо internal ТОЛЬКО ради тестов — обычно плохая практика, предполагается что тесты на публичные методы класс уже достаточно unit. но тут уже на вкус и цвет :)
| /** | ||
| * Searches for the next subtree in order | ||
| */ | ||
| private fun findMinimumTree(givenTree: Subtree): Subtree { |
There was a problem hiding this comment.
Оч странный публичный метод, непонятно из названия о чем речь, если в остальном ваш класс - это просто мапа
| val tree = reference("tree_id", TreesTable) | ||
| } | ||
|
|
||
| internal class AvlSubtree(id: EntityID<Int>) : IntEntity(id) { |
There was a problem hiding this comment.
Аналогично комменту про TreeDatabase
| throw IOException("Session failed", exeption) | ||
| } | ||
|
|
||
| } override fun close() { |
There was a problem hiding this comment.
Форматирование?) Добавьте ktlint какой-нибудь, чтобы он орал каждый раз, если забываете пока на автомате Ctrl+Alt+L жать :)
| * in other cases returns exception | ||
| */ | ||
| fun setTree(treeName: String, currentTree: AVLTree<*, String>, typeKey: String): Unit = transaction(db) { | ||
| if (typeKey != "Int" && typeKey != "String") throw IllegalStateException("Saving this type of key is not supported in the tree") |
There was a problem hiding this comment.
Здесь и еще по коду кое-где - лучше кидать какие-то кастомные свои эксепшны о таких вещах, а не дженерик IllegalState
| file.writeText(serialized) | ||
| } | ||
|
|
||
| fun getNamesTrees(): Any { |
There was a problem hiding this comment.
Возвращать Any - плохой дизайн, нужно лучше возиться с системой типов. Это вообще очень мощная штука, на курсе по функционалкам это хорошо дают понять)
|
|
||
| @TestMethodOrder(MethodOrderer.OrderAnnotation::class) | ||
| class SqliteRepAVLTest { | ||
| private val repo = SqliteRepAVL("src/main/kotlin/database/sqlite/TestDatabase") |
There was a problem hiding this comment.
Это не совсем мок, конечно, - а что если бы SQLitе была не просто файликом?)
Но в целом, идея правильная.
Почитайте еще про dependency injection (DI) и том как его правильно делать, полезно будет. В котлине юзают Koin или Kodein обычно (но может и я отстал от моды уже лол). В этих же фреймворках обычно есть все чтобы мокать такие вещи.
Implementation of graphic interface for trees
Fixed removing when input is empty
👋! GitHub Classroom created this pull request as a place for your teacher to leave feedback on your work. It will update automatically. Don’t close or merge this pull request, unless you’re instructed to do so by your teacher.
In this pull request, your teacher can leave comments and feedback on your code. Click the Subscribe button to be notified if that happens.
Click the Files changed or Commits tab to see all of the changes pushed to
mainsince the assignment started. Your teacher can see this too.Notes for teachers
Use this PR to leave feedback. Here are some tips:
mainsince the assignment started. To leave comments on specific lines of code, put your cursor over a line of code and click the blue + (plus sign). To learn more about comments, read “Commenting on a pull request”.main. Click a commit to see specific changes.For more information about this pull request, read “Leaving assignment feedback in GitHub”.
Subscribed: @PavlushaSource @AlexShmak @ALanovaya